function [out2] = measure2(arg);

persistent out hf h1 h2 hsct hl hpt hp y0 xi yi index mv cx vx tx maxindex fig pointer% data is static
if(nargin==0)
   arg=0;
end;
switch(arg)
case 0
   out = [];
   scrsz = get(0,'ScreenSize'); % determine the position of the figure in the system window
   size=0.4;
   scrb = scrsz(4)*((1-size)/2);
   scrl = scrsz(3)*((1-size)/2);
   scrwd = scrsz(3)*size;
   scrht = scrsz(4)*size;
   
   hf = findobj('Tag', 'Measure'); % check for pre-existing window
   if(isempty(hf)) % if none, make one
      hf = figure('Color', 'white', ...
         'Colormap',[1,1,1], ...
         'Position', [scrl, scrb, scrwd, scrht], ...
         'Name', 'Measure', ...
         'NumberTitle', 'off', ...
         'Tag','Measure');
      
   end
   figure(hf); % otherwise, select the existing one and overwrite it
   clf; % always clear the window...
   
   set(hf, 'Units', 'characters');
   figsz=get(hf, 'Position');
   
   b_ht = 1.7;
   pad_check = 7; pad_edit = 5; pad_list = 5; pad_pop = 7;
   pad_push = 4; pad_radio = 7; pad_static = 4;
   but_vpad = 0.125;
   but_hpad = 1.5;
   
   but_vspc = b_ht + but_vpad; % space to allocate for each button or field
   
   buttonlist = [];
   buttonlist = add_button(buttonlist, 'Next', 'measure2(6)', 'Next Record', 'Next', 'on');
   buttonlist = add_button(buttonlist, 'Prev', 'measure2(7)', 'Prev Record', 'Prev', 'on');
   buttonlist = add_button(buttonlist, 'Next+10', 'measure2(9)', 'Next Record+10', 'Next+10', 'on');
   buttonlist = add_button(buttonlist, 'Prev-10', 'measure2(10)', 'Prev Record-10', 'Prev-10', 'on');
   buttonlist = add_button(buttonlist, 'Compute', 'measure2(11)', 'compute', 'compute', 'on');
   buttonlist = add_button(buttonlist, 'Clear', 'measure2(12)', 'clear', 'clear', 'on');
   buttonlist = add_button(buttonlist, 'Dismiss', 'measure2(8)', 'Dismiss', 'Dismiss', 'on', 1);
   
   maxtitle = 0;
   for i=1:length(buttonlist)
      l = length(buttonlist(i).title);
      if(l > maxtitle) maxtitle = l;
      end
   end
   but_width = maxtitle+2*but_hpad;
   button_x = figsz(3) - but_width-but_hpad;  % place the buttons to the right side of the display
   button_y = figsz(4)*0.75-1;
   
   cmd_vspc = but_vspc + 2*but_vpad; % extra padding
   for i=1:length(buttonlist)
      b_y = button_y-i*cmd_vspc;
      if(~isempty(buttonlist(i).pos))
         b_y = 1;
      end
      h1=uicontrol('Parent', hf, ...
         'Units', 'characters', ...
         'FontUnits', 'points', ...
         'FontName', 'Arial', ...
         'FontSize', 9, ...
         'ForegroundColor', 'blue', ...
         'Position', [button_x b_y but_width+0.5 b_ht], ...
         'String', buttonlist(i).title, ...
         'Callback', buttonlist(i).callback, ...
         'Enable', buttonlist(i).enable, ...
         'Tag', buttonlist(i).tag);
   end
   
   
   
   h1 = textentry('Coord', 'Coords', sprintf('x: %+7.2f, y: %+7.2f  dy: %+7.2f ref: %+7.2f', 0, 0, 0, 0), ...
      50, 0.05, 0.90);
   set(h1, 'FontName', 'FixedWidth', 'HorizontalAlign', 'left')
   pos=get(h1, 'Position');
   ex=get(h1, 'Extent');
   pos(3)=ex(3)+2; pos(4)=ex(4);
   set(h1, 'Position', pos);
   
   h2 = textentry('RecV', 'Rec, V', sprintf('R: %4d, V: %+7.2f mV', 0, 0), ...
      40, 0.05, 0.05);
   set(h1, 'FontName', 'FixedWidth', 'HorizontalAlign', 'left')
   pos=get(h1, 'Position');
   ex=get(h1, 'Extent');
   pos(3)=ex(3)+2; pos(4)=ex(4);
   set(h1, 'Position', pos);
   %axis([0 10 0 10])
   DFILE=datac('getdfile'); % we get the data from the curren DATAC records
   maxindex=length(DFILE.record);
   [c, time]=datac('geti'); % get the currents and the time;
   % filter the current traces
   % According to Colquhoun and Sigworth (Pratical Analysis of Records, Chapter 19 in
   % Sakmann and Neher, Single Channel Recording)
   % the optimal filter is Gaussian for the first
   % pass of analysis. So, we use here their Gaussian filter.
   % the filter itself is in Gaussian.m in pbm_tools
   
   fsamp = 1000/(DFILE.nr_channel*DFILE.rate); % get sampling frequency
   fco = 0.05;		% cutoff frequency units of sample frequency
   if(fco < 1) % if fco is > 1 then this is not a filter!
      hm=msgbox('Filtering, Please Wait');
      c = gaussian(c, fco); % filter all the traces...
      close(hm);
   end
   v=datac('getv');
   index=1;
   cx=c(:,[60:1500]); % window the data;
   vx=v(:,[60:1500]);
   tx=time([60:1500]);
   c1=cx(index,:); % just get one trace to test.
   
   v1=vx(index,:);
   mv=mean(mean(v1));
   set(h2, 'String', sprintf('R: %4d, V: %+7.2f mV', index, mv));
   
   hold on
   % Initially, the list of points is empty.
   x = [];
   y = [];
   y0=0;
   n = 0;
   hp=plot(tx, c1);
   ax=axis % get axis limits for lines we draw
   hl=[];
   hpt=[];
   pointer = get(gcf,'pointer');
   set(gcf,'pointer','fullcrosshair');
   set(hf, 'Interruptible', 'off', 'BusyAction', 'cancel'); % prevent caffiene jitters from generating errors.
   set(hf, 'WindowButtonMotionFcn', 'measure2(1)');
   set(hf, 'WindowButtonDownFcn', 'measure2(2)');
   return;
   
   %---------------
   %   Update x, y measurements based on the cursor position
case 1
   hcw=get(0, 'PointerWindow');
   if(~isempty(hcw) & hcw == hf) % this is our figure
      fig_units = get(hf,'units');
      set(hf, 'units', 'pixels');
      scrn_pt = get(0,'PointerLocation');
      loc = get(hf,'Position');
      pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
      set(hf, 'CurrentPoint', pt);
      pt=get(gca, 'CurrentPoint');
      xl=get(gca, 'Xlim');
      yl=get(gca, 'Ylim');
      if((pt(1,1) >= xl(1)) & (pt(1,1) <= xl(2)) & (pt(1,2) >= yl(1)) & (pt(1,2) <= yl(2)))
         set(h1, 'String', sprintf('x: %+7.2f, y: %+7.2f  dy: %+7.2f ref: %+7.2f', pt(1,1), pt(1,2), pt(1,2)-y0, y0));
      end;
      set(hf,'units',fig_units); % restore units...
   end;
   %-----------------
   % This is what we do with a button down... 
case 2
   hcw=get(0, 'PointerWindow');
   if(hcw == hf) % this is our figure
      b=[];
      fig_units = get(hf,'units');
      set(hf, 'units', 'pixels');
      scrn_pt = get(0,'PointerLocation');
      loc = get(hf,'Position');
      pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
      set(hf, 'CurrentPoint', pt);
      pt=get(gca, 'CurrentPoint');
      xl=get(gca, 'Xlim');
      yl=get(gca, 'Ylim');
      if((pt(1,1) >= xl(1)) & (pt(1,1) <= xl(2)) & (pt(1,2) >= yl(1)) & (pt(1,2) <= yl(2)))
         xi=pt(1,1);
         yi=pt(1,2);
      end;
      % determine the button status
      button = get(hf, 'SelectionType');
      if strcmp(button,'open')
         button = 0;
      elseif strcmp(button,'normal')
         button = 1;
      elseif strcmp(button,'extend')
         button = 2;
      elseif strcmp(button,'alt')
         button = 3;
      else
         disp('Invalid mouse selection.')
      end
      switch(button) % then do what we need to do to read the data.
      case 0 % double click is "open"
         disp(sprintf('mv: %7.2f  dy: %7.2f', mv, yi-y0))
         out=[out; [mv (yi-y0)]];
      case 1 % left button - draw a crosshair
         if(isempty(hpt))
            hpt=plot(xi,yi,'g+', 'MarkerSize', 24, 'EraseMode', 'xor'); % Mark absolute position
         else
            set(hpt, 'XData', xi, 'YData', yi);
         end;
         set(hpt, 'Visible', 'on');
      case 3
         [xi yi xl yl] = read_pos(hf, hpt);
         if(~isempty(xi))
            if(isempty(hl)) % first line we e draw
               hl=line(xl, [yi yi], 'Color', 'k', 'LineStyle', '--', 'EraseMode', 'xor');
            else
               set(hl, 'Ydata', [yi yi]);
            end;
            y0=yi; % that's the NEW reference point
            set(h1, 'String', sprintf('x: %+7.2f y: %+7.2f dy: %+7.2f ref: %+7.2f', xi, yi, yi-y0, y0));
         end;
      otherwise
         if(~isempty(xi))
            set(h1, 'String', sprintf('x: %+7.2f y: %+7.2f dy: %+7.2f ref: %+7.2f', xi, yi, yi-y0, y0));
         end;
      end;
   end;
   
case 3 % right button context choice- draw a reference line
   disp('3');
   [xi yi xl yl] = read_pos(hf, hpt);
   disp(sprintf('xi: %f yi: %f', xi, yi))
   if(~isempty(xi))
      if(isempty(hl)) % first line we e draw
         disp('new line');
         hl=line(xl, [yi yi], 'Color', 'k', 'LineStyle', '--', 'EraseMode', 'xor');
      else
         set(hl, 'Ydata', [yi yi]);
      end;
      y0=yi; % that's the NEW reference point
      set(hp, 'LineStyle', '--');
      set(h1, 'String', sprintf('x: %+7.2f y: %+7.2f dy: %+7.2f ref: %+7.2f', xi, yi, yi-y0, y0));
   end;
case 4
case 5
case 6
   index=index+1;
   if(index > maxindex)
      disp(' Index beyond range');
      index=index-1;
      return;
   end;
   c1=cx(index,:); % just get one trace to test.
   v1=vx(index,:);
   mv=mean(mean(v1));
   set(h2, 'String', sprintf('R: %4d, V: %+7.2f mV', index, mv));
   axis auto;
   set(hp, 'Ydata', c1);
   
case 7
   index=index-1;
   if(index < 1)
      disp(' Index beyond range');
      return;
   end;
   c1=cx(index,:); % just get one trace to test.
   v1=vx(index,:);
   mv=mean(mean(v1));
   set(h2, 'String', sprintf('R: %4d, V: %+7.2f mV', index, mv));
   axis auto
   set(hp, 'Ydata', c1);
   
case 9
   index=index+10;
   if(index > maxindex)
      disp(' Index beyond range');
      index=index-1;
      return;
   end;
   c1=cx(index,:); % just get one trace to test.
   v1=vx(index,:);
   mv=mean(mean(v1));
   set(h2, 'String', sprintf('R: %4d, V: %+7.2f mV', index, mv));
   axis auto
   set(hp, 'Ydata', c1);
   
case 10
   index=index-10;
   if(index < 1)
      disp(' Index beyond range');
      return;
   end;
   c1=cx(index,:); % just get one trace to test.
   v1=vx(index,:);
   mv=mean(mean(v1));
   axis auto
   set(h2, 'String', sprintf('R: %4d, V: %+7.2f mV', index, mv));
   set(hp, 'Ydata', c1);
   
case 11
   h_sciv = findobj('Tag', 'sciv'); % check for pre-existing window
   if(isempty(h_sciv)) % if none, make one
      h_sciv = figure('Color', 'white', ...
         'Colormap',[1,1,1], ...
         'Name', 'SC-IV', ...
         'NumberTitle', 'off', ...
         'Tag','sciv');
   end
   
   figure(h_sciv); % otherwise, select the existing one and overwrite it
   clf; % always clear the window...
   hsct=findobj('Tag', 'SC');
   if(isempty(hsct))
      hsct = textentry('SC', 'Conductance', sprintf(' %+7.2f pS Rev: %+7.2f mV ', 0, 0, 0), ...
         50, 0.05, 0.05);
   end;
   [m b p r] = linreg(out(:,1), out(:,2));
   yi=m*out(:,1)+b;
   rev = -b/m; % potential where current would be 0
   set(hsct, 'String', sprintf('%7.2f pS Rev = %7.1f mV', 1000*m, rev));
   plot(out(:,1), out(:,2), 'LineStyle', 'none', 'Marker', 'o');
   hold on
   plot(out(:,1), yi, 'LineStyle', '-', 'Color', 'k');
   hold off;
case 12
   out=[]; % reset the list
   
case 8
   out2 = out;
   set(hf, 'WindowButtonMotionFcn', 'measure2(1)');
   set(hf, 'WindowButtonDownFcn', 'measure2(2)');
   
   set(fig,'pointer',pointer);
   close;
   return;
otherwise
end;


return;


function [xi, yi, xl, yl] = read_pos(hf, hpt)
xi=[]; yi=[];
hcw=get(0, 'PointerWindow');
if(hcw == hf) % this is our figure
   % hide the crosshair we drew
   if(~isempty(hpt))
      set(hpt, 'Visible', 'off');
   end;
   b=[];
   fig_units = get(hf,'units');
   set(hf, 'units', 'pixels');
   scrn_pt = get(0,'PointerLocation');
   loc = get(hf,'Position');
   pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
   set(hf, 'CurrentPoint', pt);
   pt=get(gca, 'CurrentPoint');
   xl=get(gca, 'Xlim');
   yl=get(gca, 'Ylim');
   if((pt(1,1) >= xl(1)) & (pt(1,1) <= xl(2)) & (pt(1,2) >= yl(1)) & (pt(1,2) <= yl(2)))
      xi=pt(1,1);
      yi=pt(1,2);
   end;
   set(hf,'units',fig_units); % restore units...
   
end;
return;





% textentry.m - make a textbox with a label
% call: textbox(tag, label, initvalue, x, y)
% x and y are in character units...
function [handle] = textentry(tag, label, initvalue, fieldwidth, x, y)


b_ht = 1.4; % standard field height in characters
pad_static=4;
pad_edit=5;
fontsz=10;
fwtitle = length(label)+pad_static;
fwarg = fieldwidth+pad_edit - fwtitle;
if(fwarg < (length(initvalue)+pad_edit+1)) fwarg=length(initvalue)+pad_edit+1;
end
h1 = uicontrol('Units','characters', ...
   'ListboxTop',0, ...
   'Position',[x y fwtitle b_ht], ...
   'HorizontalAlignment','left', ...
   'String',label, ...
   'Style','text', ...
   'FontSize', fontsz);
handle = uicontrol('Units','characters', ...
   'ListboxTop',0, ...
   'background', [1 1 1], ...
   'foreground', 'black', ...
   'Position',[x+fwtitle y fwarg b_ht], ...
   'HorizontalAlignment','right', ...
   'Max', 1, ...
   'Min', 0, ...
   'Style','edit', ...
   'FontSize', fontsz, ...
   'Tag',tag);
set(handle, 'String', initvalue);
return
